package com.sisyphus.spinach.helper;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;
import android.widget.TextView;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

// 默认时间为60秒
@SuppressLint("StringFormatMatches")
public class LifecycleCountDownTimer extends CountDownTimer implements LifecycleObserver {

    private static final long COUNT_DOWN_INTERVAL = 1000;

    private TextView mTextView;
    private String mText, mFormat;


    public LifecycleCountDownTimer(Lifecycle lifecycle, TextView view) {
        this(60 * 1000, lifecycle, view, null);
    }

    public LifecycleCountDownTimer(int seconds, Lifecycle lifecycle, TextView view) {
        this(seconds, lifecycle, view, null);
    }

    public LifecycleCountDownTimer(
            int seconds, // 秒
            Lifecycle lifecycle, // 绑定生命周期
            TextView view, // 显示的View
            String format // 显示的字符串
    ) {
        super(seconds, COUNT_DOWN_INTERVAL);
        mTextView = view;
        mFormat = format;
        mText = view.getText().toString();
        lifecycle.addObserver(this);
    }


    @Override
    public void onFinish() {
        mTextView.setText(mText);
        mTextView.setEnabled(true);
    }


    @Override
    public void onTick(long millisUntilFinished) {
        mTextView.setEnabled(false);

        long args = millisUntilFinished / COUNT_DOWN_INTERVAL;

        if (mFormat == null) {
            mTextView.setText(String.valueOf(args));

        } else {
            mTextView.setText(String.format(mFormat, args));
        }
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy() {
        // 取消倒计时
        this.cancel();
    }

}
